//
//  XJCustomIdentityViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/7/7.
//  Copyright © 2018年 Tzyang. All rights reserved.
//

#import "XJCustomIdentityViewController.h"
//view
#import "XJIdentityUpLoadIdCardImgView.h"
#import "XJIdentityChickView.h"

//model
#import "XJIdCheckModel.h"

//vendow
#import <QiniuSDK.h>
#import <TZImagePickerController.h>

typedef NS_ENUM(NSInteger, XJSelectImgType) {
    XJSelectImgFrontType, //正面
    XJSelectImgBackType, //反面
    XJSelectImgHandType  //手持省份证
};
@interface XJCustomIdentityViewController ()<TZImagePickerControllerDelegate>
//还需要定义三个变量判断是否选择了图片 七牛云上传之后会有一个回调。回调中会返回一个url
{
    NSString *_front_imageStr;//是否选择了身份证正面
    NSString *_behind_imageStr;//是否选择了身份证背面
    NSString *_hand_imageStr;//是否选择的手持身份证照片
    
    NSString *_token; //临时存储七牛云token
}

@property (weak, nonatomic) IBOutlet UITextField *nameTF; //姓名LB

@property (weak, nonatomic) IBOutlet UIButton *manButton; //男按钮
@property (weak, nonatomic) IBOutlet UIButton *womanButton; //女按钮

@property (weak, nonatomic) IBOutlet UITextField *idCardTF; //省份证号码Lb


//----------------------------
/**性别*/
@property (nonatomic, copy) NSString *sex;
/**上传身份照片view*/
@property (nonatomic, strong) XJIdentityUpLoadIdCardImgView *uploadImgView;
/**正在审核中view*/
@property (nonatomic, strong) XJIdentityChickView *idIsChickingView;
/**选择的图片种类*/
@property (nonatomic, assign) XJSelectImgType selImgType;
/**实名认证状态 1 正在审核 2 已经认证  3 未认证*/
@property (nonatomic, strong) NSNumber *state;

@end

@implementation XJCustomIdentityViewController

#pragma mark - 一 lazy

- (XJIdentityUpLoadIdCardImgView *)uploadImgView {
    if (!_uploadImgView) {
        //xib view 使用 self.view.bound 不准。
        _uploadImgView = [[XJIdentityUpLoadIdCardImgView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight)];
        
//        //上传身份证正面
        UITapGestureRecognizer *frontTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(frontIvAction:)];
        [_uploadImgView.fromtIv addGestureRecognizer:frontTap];

        //        //上传身份证反面
        UITapGestureRecognizer *backTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backTapAction:)];
        [_uploadImgView.backIv addGestureRecognizer:backTap];

        //        //手持身份
        UITapGestureRecognizer *handTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handTapIvAction:)];
        [_uploadImgView.handIv addGestureRecognizer:handTap];
        
       
        //下一步
        [_uploadImgView.idUploadIdCardViewNextBtn addTarget:self action:@selector(uploadIdCardIvNextButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
        _uploadImgView.hidden = NO; //默认隐藏

    }
    return _uploadImgView;
}

- (XJIdentityChickView *)idIsChickingView {
    if (!_idIsChickingView) {
        //如果是xib的话不能用view.bounds 设置frame
//        _idIsChickingView = [[XJIdentityChickView alloc] initWithFrame:self.view.bounds];
        
        _idIsChickingView = [[XJIdentityChickView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight - kStatusBarAndNavigationBarHeight)];
    }
    return _idIsChickingView;
}

#pragma mark - 二 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
   
    [self setupView];
    
    [self cuttentTimeStr];
    
    [self requestISIdentity];
    
    [self requestQiNiuToken];
}

- (void)setupView {
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"实名认证";
    
    [self settingViewStyle];
    
//    self.nameTF.text = @"张三";
//    self.sex = @"1";
//    self.idCardTF.text = @"1234J56";
    
    self.uploadImgView.hidden = YES;
    [self.view addSubview:self.uploadImgView];
    
    self.idIsChickingView.hidden = YES; //根据请求结果控制他的hidden属性
    [self.view addSubview:self.idIsChickingView];
    
    
    //1 正在审核 2 已认证 3未认证
    NSNumber *state = self.identityState;
    
    if ([state isEqualToNumber:@1]) { //审核中
        self.idIsChickingView.hidden = NO;
        self.uploadImgView.hidden = YES;

    }else if ([state isEqualToNumber:@2]){ //已认证

    }else if ([state isEqualToNumber:@3]) { //未认证

        self.idIsChickingView.hidden = YES;
        self.uploadImgView.hidden = YES;
    }else {
        XJLog(@"");
    }
}

//对Xib中的部分控件设置样式
- (void)settingViewStyle {
    //男button
    self.manButton.layer.masksToBounds = YES;
    self.manButton.layer.cornerRadius = 10;
    
    self.manButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.manButton.layer.borderWidth = 1.0;
    
    //女button
    self.womanButton.layer.masksToBounds = YES;
    self.womanButton.layer.cornerRadius = 10;
    
    self.womanButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.womanButton.layer.borderWidth = 1.0;
}


#pragma mark - 点击事件
//男
- (IBAction)clickManButtonAction:(UIButton *)sender {
    sender.backgroundColor = XJCOLOR_RGB(255, 218, 67);
    self.womanButton.backgroundColor = [UIColor whiteColor];
    
    self.sex = @"男";
}

//女
- (IBAction)clickWomanButtonAction:(UIButton *)sender {
    
    sender.backgroundColor = XJCOLOR_RGB(255, 218, 67);
    self.manButton.backgroundColor = [UIColor whiteColor];
    
    self.sex = @"女";
}


//下一步
- (IBAction)clickNextButtonAction:(UIButton *)sender {
    
    NSString *name = self.nameTF.text;
    NSString *idCardStr = self.idCardTF.text;
    
    if ([NSString isEmptyString:name]) {
        [JRToast showWithText:@"未来巴扎:请输入真实姓名"];
        return;
    }
    
    if ([NSString isEmptyString:self.sex]) {
        [JRToast showWithText:@"未来巴扎:请选择性别"];
        return;
    }
    
    if ([NSString isEmptyString:idCardStr]) {
        [JRToast showWithText:@"未来巴扎:请输入身份证号"];
        return;
    }
    
    
//    if (idCardStr.length != 18) {
//        [JRToast showWithText:@"未来巴扎:身份证号长度不正确"];
//        return;
//    }
 
    XJLog(@"下一步");
    
    // 下一步验证通过 回收键盘 显示上身份证view 。
    [self.view endEditing:YES];
    
    self.uploadImgView.hidden = NO;
}



#pragma mark - 四 - 上传身份证按钮点击事件
/**身份证正面*/
- (void)frontIvAction:(UITapGestureRecognizer *)tap {
    XJLog(@"身份证正面");
    self.selImgType = XJSelectImgFrontType;
//    [self presentImgPicker];
    [self configureTzImagePickerVc];
}

- (void)backTapAction:(UITapGestureRecognizer *)tap{
    XJLog(@"身份证背面");
    self.selImgType = XJSelectImgBackType;
//    [self presentImgPicker];
    [self configureTzImagePickerVc];
}

- (void)handTapIvAction:(UITapGestureRecognizer *)tap {
    XJLog(@"手持身份证");
    self.selImgType = XJSelectImgHandType;
//    [self presentImgPicker];
    [self configureTzImagePickerVc];
}

- (void)uploadIdCardIvNextButtonAction:(UIButton *)button {
    XJLog(@"上传身份证下一步");
    //调用实名认证的接口
    if ([NSString isEmptyString:_front_imageStr]) {
        [JRToast showWithText:@"请上传身份证正面图片"];
        return;
    }
    if ([NSString isEmptyString:_behind_imageStr]) {
        [JRToast showWithText:@"请上传身份证背面图片"];
        return;
    }
    if ([NSString isEmptyString:_hand_imageStr]) {
        [JRToast showWithText:@"请上传手持身份证图片"];
        return;
    }
    
    //组装请求参数
    NSString *realname = self.nameTF.text;
    NSString *sex = self.sex;
    NSString *identity_card = self.idCardTF.text;
    NSString *front_image = _front_imageStr;
    NSString *behind_image = _behind_imageStr;
    NSString *hand_image = _hand_imageStr;
    
    NSDictionary *parDic = NSDictionaryOfVariableBindings(realname,sex,identity_card,front_image,behind_image,hand_image);
    
    [self requestTiJiaoShenHeWithParDic:parDic];

}




#pragma mark - 五 七牛上传图片

//TZImagePickerControllerDelegate
#pragma mark - 六  TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    
    
    XJLog(@"===%ld",photos.count);
    
    UIImage *selImg = [photos lastObject];
    //将当前时间作为图片的名字
    NSString *selImgStr = [NSString stringWithFormat:@"%@.jpg",[self cuttentTimeStr]];
    //将图片转为NSData
    NSData *selImgData = UIImagePNGRepresentation(selImg);
    
    //使用七牛云上传图片。
    
    if([NSString isEmptyString:_token]) {
        XJLog(@"获取七牛云token失败。请重新获取");
        return;
    }
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    [upManager putData:selImgData key:selImgStr token:_token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        NSString *imgUrl = resp[@"url"];
        
        if (self.selImgType == XJSelectImgFrontType) {
            self.uploadImgView.fromtIv.image = selImg;
            _front_imageStr = imgUrl;
            
        }else if (self.selImgType == XJSelectImgBackType) {
            self.uploadImgView.backIv.image = selImg; //要取最后一个元素
            _behind_imageStr = imgUrl;

            
        }else if (self.selImgType == XJSelectImgHandType) {
            self.uploadImgView.handIv.image = selImg; //要取最后一个元素
            _hand_imageStr = imgUrl;

        }else {
            XJLog(@"--------");
        }

    } option:nil];
}


#pragma mark - 七 网络请求
/**监测是否进行了实名认证*/
- (void)requestISIdentity {
    [XJHttpTool requestCustomIsIdentitySuccesH:^(id responseObjc) {

        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        
        if ([code isEqualToString:@"0"]) {
        
            NSDictionary *identityDic = responseObjc[@"data"][@"identity"];
            
           NSArray *idCheckModelArr = [self assembleIsCheckViewDataWithDic:identityDic];
            
            NSNumber *state = responseObjc[@"data"][@"identity"][@"status"];

            //更具状态判断:显示不同的view
            //1为正在审核，2审核通过，3为审核失败
            if ([state isEqualToNumber:@1] || [state isEqualToNumber:@2]) {
                self.idIsChickingView.hidden = NO; //显示
                [self.idIsChickingView configureXJIdentityChickViewWithDataArray:idCheckModelArr stateStr:state];

                self.uploadImgView.hidden = YES; //隐藏
                
            }else { //都隐藏
                self.uploadImgView.hidden = YES;
                self.idIsChickingView.hidden = YES;
            }
        }
        
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}


/**获取七牛云token*/
- (void)requestQiNiuToken {
 
    [XJHttpTool requestQiNiuTokenSuccessH:^(id responseObjc) {
       
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            _token = responseObjc[@"data"][@"token"];
        }
    } fialH:^(NSError *error) {
        XJLog(@"获取七牛云token失败:%@",error);
    }];
}


/**进行实名认证*/
- (void)requestTiJiaoShenHeWithParDic:(NSDictionary *)parDic {
    [XJHttpTool requetCustomIdentityWithParDic:parDic successH:^(id responseObjc) {
        NSData *jsonDAta = [NSJSONSerialization dataWithJSONObject:responseObjc options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr = [[NSString alloc] initWithData:jsonDAta encoding:NSUTF8StringEncoding];
        XJLog(@"%@",jsonStr);
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            //让 XJIdentityChickView 显示
            
            self.idIsChickingView.hidden = NO;
            
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
            self.idIsChickingView.hidden = YES;
        }
        
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}
#pragma mark - 七 Private method

- (void)configureTzImagePickerVc {
    TZImagePickerController *tzIImgpickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    [self presentViewController:tzIImgpickerVc animated:YES completion:nil];
}



//将当请系统时间作为图片的名字
- (NSString *)cuttentTimeStr {
    NSDate *date = [NSDate date];
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyyMMddHHmmss";
    
    NSString *currentStr = [fmt stringFromDate:date];
    XJLog(@"=====>:%@",currentStr);
    
    return currentStr;
}

/**如果正在进行实名认证就将服务器返回的dic进行组装。转model存字典。然后过给
 
 "XJIdCheckModel.h  (leftStr;  rightStr);

 
 XJIdCheckCell.h"
 */
- (NSArray *)assembleIsCheckViewDataWithDic:(NSDictionary *)dic {
    
    //怎么判断字典是否为空？
    if ([dic allKeys].count == 0) return nil;
    
    
    //组装成字典
    NSDictionary *dic1 = @{@"leftStr":@"真实姓名",
                           @"rightStr":dic[@"realname"],
                           };
    NSNumber *sex = dic[@"sex"];
    NSString *sexStr = [sex isEqualToNumber:@1] ? @"男" : @"女";
    NSDictionary *dic2 = @{@"leftStr":@"性别",
                           @"rightStr":sexStr
                           };
    NSString *identity_card = dic[@"identity_card"];
    NSString *daMaIDCard = [self daMaWithIDCard:identity_card];
    NSDictionary *dic3 = @{@"leftStr":@"身份证号码",
                           @"rightStr":daMaIDCard
                        };
    
    NSMutableArray *dicArr = @[dic1,dic2,dic3].mutableCopy;
    
   
    NSMutableArray *newArr = [NSMutableArray array];
    
    // 转模型
    for (NSDictionary *tempDic in dicArr) {
        XJIdCheckModel *model = [XJIdCheckModel mj_objectWithKeyValues:tempDic];
        
        [newArr addObject:model];
    }
    
    return [newArr copy];
}

- (NSString *)daMaWithIDCard:(NSString *)idCard {
    //123************3456
    NSInteger len = idCard.length;
    
    NSRange r1 = NSMakeRange(0, 3);
    NSRange r2 = NSMakeRange(len-4, 4);
    
    NSString *str1 = [idCard substringWithRange:r1];
    NSString *str2 = [idCard substringWithRange:r2];
    
    NSMutableString *centerStrM = [NSMutableString string];
    for (NSInteger i = 3; i<len-4; i++) {
        [centerStrM appendFormat:@"*"];
    }
    
    NSString *daMaStr = [NSString stringWithFormat:@"%@%@%@",str1,centerStrM,str2];
    
    XJLog(@"打码后的字符串:%@",daMaStr);
    return daMaStr;
}
/**
 {
 "data" : {
 "message" : null,
 "identity" : {
 "id" : 24,
 "uuid" : "25310990",
 "front_image" : "upload\/auth\/2018_03_23\/2767c3a16d1544f2845c76fb92b9e961.jpg",
 "sex" : 1,
 "realname" : "啊啊啊",
 "behind_image" : "upload\/auth\/2018_03_23\/cb8cc36cfed84ce9a40cd7432aa150d1.jpg",
 "hand_image" : "upload\/auth\/2018_03_23\/8793243020a24ef6922198d1aa7f4a6d.jpg",
 "is_rejected" : 0,
 "customer_id" : 7,
 "identity_card" : "123456789456123458",
 "create_time" : 1531296087073,
 "status" : 1
 }
 },
 "code" : 0
 }

 */


// 将color 转为image
- (UIImage *)imageFromColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    
    UIGraphicsBeginImageContext(rect.size);
    
    // 获取当前上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // 设置颜色
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    // 填充矩形区域
    CGContextFillRect(context, rect);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return img;
}

#pragma mark - 逻辑
/**
 2个自定义view
 XJIdentityUpLoadIdCardImgView.
 XJIdentityChickView
 
通过控制 hidden 属性实现相应效果
 
 
 if (实名认证) XJIdentityChickView 显示
 
 else 走实名认证逻辑。信息填写完整控制 XJIdentityUpLoadIdCardImgView 的hidden为NO. 点击下一步根据请求结果判断 对应的去控制XJIdentityChickView 的hidden属性。
 */
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

